import 'package:flutter/material.dart';
import 'package:flutter_base_framework/flutter_base_framework.dart';
import 'package:flutter_common_utils/flutter_common_utils.dart';
import 'package:flutter_live_data/live_data_export.dart';
import 'base_view_model.dart';
import 'package:flutter_refresh/flutter_refresh_export.dart';
import 'package:flutter_common_ui/flutter_common_ui.dart';

///自定义Widget  BaseWidget 方便管理StatefulWidget，整个项目基础组件,包括页面
///基础者内部属性必须final
abstract class BaseWidget extends StatefulWidget {
  const BaseWidget({super.key});
}

///自定义Widget
abstract class BaseWidgetState<T extends BaseWidget> extends State<T> with WidgetsBindingObserver, LifecycleOwner {
  //页面状态切换
  LoadStateController? loadStateCtrl;

  //下拉刷新和加载更多分页
  AppRefreshController? refreshCtrl;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  void initLoadStateCtrl() {
    loadStateCtrl = loadStateCtrl ?? LoadStateController();
  }

  void initRefreshCtrl() {
    refreshCtrl = refreshCtrl ?? AppRefreshController();
  }

  @override
  void dispose() {
    super.dispose();
    refreshCtrl?.dispose();
    loadStateCtrl?.dispose();
    WidgetsBinding.instance.removeObserver(this);
    BaseCoreConfig.onDispose(this);
  }
}

class _NullWidget extends StatelessWidget {
  const _NullWidget();

  @override
  Widget build(BuildContext context) {
    throw FlutterError(
      'Widgets that mix BaseWidgetState into their State must '
      'call super.build() but must ignore the return value of the superclass.',
    );
  }
}

///自定义Widget
abstract class BaseMvvmWidgetState<T extends BaseWidget, VM extends BaseViewModel> extends BaseWidgetState<T> {
  //主要的ViewMode
  late VM vm;

  BaseMvvmWidgetState(VM? vvm) {
    initVm(vvm);
  }

  void initVm(VM? vvm) {
    if (vvm != null) {
      vm = vvm;
    }
  }

  @override
  void initState() {
    super.initState();
    if (vm.lifecycleOwner != this) {
      vm.isFirst = true;
    }
    vm.lifecycleOwner = this;
    vm.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    LogUtils.i("didChangeDependencies :$runtimeType");
  }

  @override
  void didUpdateWidget(covariant T oldWidget) {
    super.didUpdateWidget(oldWidget);
    LogUtils.i("didUpdateWidget :$runtimeType");
  }

  @override
  void deactivate() {
    super.deactivate();
    LogUtils.i("deactivate :$runtimeType");
  }

  @override
  void dispose() {
    if (!vm.isDispose) {
      vm.dispose();
    }
    super.dispose();
    LogUtils.i("销毁dispose :$runtimeType");
  }
}
